﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DynamicProxy.IInterceptor
{
    /// <summary>
    /// 异常拦截器，为指定方法添加try...cache块
    /// </summary>
    public class ExceptionInterceptorProxy : Castle.DynamicProxy.IInterceptor
    {
        private Action<string> _logger;

        #region Constructors
        public ExceptionInterceptorProxy(Action<string> logger)
        {
            _logger = logger;
        }
        public ExceptionInterceptorProxy()
            : this(null)
        { }
        #endregion

        #region IInterceptor 成员

        public void Intercept(Castle.DynamicProxy.IInvocation invocation)
        {
            try
            {
                invocation.Proceed();
            }
            catch (Exception ex)
            {
                string exceptionInfo = (DateTime.Now + "把方法拦截后，加入异常块，并对异常进行记录:" + ex.Message);
                if (_logger == null)
                    exceptionInfo.AddLogFiles("Exception.log");
                else
                    _logger(exceptionInfo);
            }

        }

        #endregion
    }
}
